package com.xiemulei.gulimall.coupon.service.impl;

import com.xiemulei.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.xiemulei.gulimall.coupon.service.SeckillSkuRelationService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiemulei.common.utils.PageUtils;
import com.xiemulei.common.utils.Query;

import com.xiemulei.gulimall.coupon.dao.SeckillSessionDao;
import com.xiemulei.gulimall.coupon.entity.SeckillSessionEntity;
import com.xiemulei.gulimall.coupon.service.SeckillSessionService;



@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Resource
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatest3DaySession() {
        // 计算开始时间和结束时间
        List<SeckillSessionEntity> list = this.list(new QueryWrapper<SeckillSessionEntity>().between("start_time", startTime(), endTime()));

        if (list != null && list.size() > 0) {
            return list.stream().peek(session -> {
                Long sessionId = session.getId();
                List<SeckillSkuRelationEntity> relationSkus = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", sessionId));
                session.setRelationSkus(relationSkus);
            }).toList();
        }
        return null;
    }

    private String startTime() {
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        return LocalDateTime.of(now, min).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    private String endTime() {
        LocalDate now = LocalDate.now();
        LocalTime max = LocalTime.MAX;
        return LocalDateTime.of(now.plusDays(2), max).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    }

}